<template>
        <dbant-loading :loading="viewLoading">
    <div class="workbeanch-sql-editor-box">
        <div class="sql-editor-toolbar">
            <el-row :gutter="10">
                <el-col :span="1.5">
                    <el-tooltip effect="light" content="执行" placement="top-start">
                        <el-button icon="el-icon-videoPlay" plain circle size="small" :disabled="!connectionId"
                            @click="sqlQueryHandle" />
                    </el-tooltip>

                </el-col>
                <el-col :span="1.5">
                    <el-tooltip effect="light" content="停止执行" placement="top-start">
                        <el-button icon="el-icon-videoPause" plain circle size="small" :disabled="!executeState"
                            @click="sqlQueryHandle" />
                    </el-tooltip>
                </el-col>
                <el-col :span="1.5">
                    <el-tooltip effect="light" content="sql美化" placement="top-start">
                        <el-button icon="el-icon-magicStick" plain circle size="small"   @click="formatSqlHandle"/>
                    </el-tooltip>
                </el-col>
                <el-col :span="1.5">
                    <el-tooltip effect="light" content="保存sql" placement="top-start">
                        <el-button icon="el-icon-folderAdd" plain circle size="small" />
                    </el-tooltip>

                </el-col>
                <el-col :span="1.5">
                    <el-tooltip effect="light" content="sql美化" placement="top-start">
                        <el-button icon="el-icon-message" plain circle size="small" />
                    </el-tooltip>

                </el-col>
            </el-row>
            <div style="padding-top:5px">
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-select v-model="connectionId" class="m-2" placeholder="选择连接" size="small" clearable filterable
                            @change="((val) => { getCatalogList(val) })">
                            <el-option v-for="item in connList" :key="item.id" :label="item.name" :value="item.id">
                                <span class="custom-tree-node menus">
                                    <el-icon style="color:#165EFF;padding-right: 2px;"><dbant-icon :icon="getIcon(item)" /></el-icon>
                                    <span> {{ item.name }}</span>
                                </span>

                            </el-option>

                        </el-select>
                    </el-col>
                    <el-col :span="1.5">
                        <el-select v-model="catalogName" class="m-2" placeholder="选择数据库" size="small" clearable filterable>
                            <el-option v-for="item in catalogList" :key="item.name" :label="item.name" :value="item.name" >
                                <span class="custom-tree-node menus">
                                    <el-icon style="color:#165EFF; padding-right: 2px;"><dbant-icon :icon="getIcon(item)" /></el-icon>
                                    <span> {{ item.name }}</span>
                                </span>
                                </el-option>

                        </el-select>
                    </el-col>
                    <el-col :span="1.5">
                        <el-tooltip effect="light" content="是否开启分页" placement="top-start">
                            <el-switch v-model="globalPageState" size="small" :active-value="false" inline-prompt plain
                                :inactive-value="true" />
                        </el-tooltip>
                    </el-col>
                </el-row>
            </div>

        </div>
        <div class="sql-editor">

            <div class="magic-monaco-editor-wrapper">
                <monaco-editor ref="sqlEditor" v-model:modelValue="sql" :language="language"
                    v-model:selectedCatalog="catalogName" :hight-change="hightChange" read-only="false"
                    @editor-mounted="editorMounted" :on-input-field="onInputField" v-model:dbs="dbs" />
            </div>
        </div>

        <div class="workbeanch-toolbar">
            <dbant-navbar direction="horizontal" :default-select="-1" ref="navbar" class="magic-navbar" :spliter="true">
                <dbant-navbar-item key="1" title="执行结果" icon="query">
                    <dbant-resizer direction="y" :max="500" :min="400" @update:value="updateExecuteResultResize">
                        <div class="sql-execute-result-box">
                                    <dbant-loading :loading="resultLoading">
                            <dbant-tabs v-bind:value="resultTabs.activeTab" >
                                <el-tab-pane label="消息" name="message" :closable="false">
                                    <el-scrollbar>
                                        <div class="result-box" :style="{ height: executeResultMessageResizerValue1 }">

                                            <div v-for="item in executeResult" class="result-message">
                                                <div>{{ item.sql }}</div>
                                                <div :style="{ color: item.success ? '' : 'red' }">>>{{ item.message }}
                                                </div>
                                                <div>>>查询时间：{{ item.time / 1000 }}秒</div>
                                            </div>

                                        </div>
                                    </el-scrollbar>
                                </el-tab-pane>
                                <el-tab-pane v-for="(item, index) in executeResultTabs" :label="`结果${index + 1}`"
                                    :key="index" :name="`结果${index + 1}`">
                                    <el-scrollbar>
                                        <execute-result v-bind:item="item" v-bind:connId="connectionId"
                                            v-bind:catalog="catalogName" v-bind:pluginId="pluginId"></execute-result>
                                    </el-scrollbar>
                                </el-tab-pane>
                            </dbant-tabs>
                            </dbant-loading>
                        </div>
                    </dbant-resizer>
                </dbant-navbar-item>
            </dbant-navbar>
        </div>
    </div>
    </dbant-loading>
</template>

<script setup>

import { ref, defineProps, inject, h, computed, nextTick, reactive, defineExpose } from 'vue'
import ExecuteResult from './resource/executeResult.vue';
import {format} from 'sql-formatter';

import _ from "lodash"
const props = defineProps({
    connId: {
        type: Number,
        default: undefined
    },
    catalog: {
        type: String,
        default: undefined
    }
});

const $api = inject('$api');
const $config = inject('$config')
const $pluginService = inject("$pluginService")
const connectionId = ref()
const pluginId = ref();
const catalogName = ref()

const viewLoading = ref(true)
const resultLoading = ref(true)
const sql = ref("SELECT * FROM  information_schema.`COLUMNS`");
const language = ref("sql");
const hightChange = "false";
const connList = ref([]);
const catalogList = ref([]);
const dbs = ref([]);
const executeState = ref(false);

const executeResult = ref([]);
const executeResultTabs = ref([])
const navbar = ref(null)
let executeResultResizerValue = ref(400)
const globalPageState = ref(false)

const resultTabs = ref({
    activeTab: 'message'
})

const initData = () => {
    $api.connection.getTree().then((res) => {
        connList.value = res.data;
         if (!props.connId || props.connId === 'undefined') {
          
            return
        }
        connectionId.value = props.connId+'';
        if(connectionId.value){
           getCatalogList(connectionId.value)
           .then(()=> catalogName.value = props.catalog)
        }
        
    }).finally(()=> viewLoading.value = false);
}
initData();


const updateExecuteResultResize = (value) => {

    executeResultResizerValue.value = value
}
const sqlEditor = ref(null)


const executeResultMessageResizerValue1 = computed(() => {
    return `${executeResultResizerValue.value - 30}px`;
});

const getIcon = (node) => {
    const pluginJs = $pluginService.getPlugin(node.properties.pluginId);
    if (!pluginJs) {
        return '#dbant-icon-'+node.type.toLowerCase();
    }
    const typeObj = pluginJs.resource[node.type.toLowerCase()];
    if (typeObj && typeObj.icon) {
        return pluginJs.resource[node.type.toLowerCase()].icon;
    }
    return node.type.toLowerCase();
}

const getCatalogList = (connId) => {
    
  return new Promise ((resolve)=>{
    catalogName.value = '';
        catalogList.value = []

        resultTabs.value.activeTab = 'message'
        if (!connId||connId==='undefined') {
            resolve()
            return
        }
        const connItem = connList.value.find(value => value.id == connId);
        pluginId.value = connItem.properties.pluginId
        catalogList.value = [];
        const params = { connId: connItem.properties.connId };
        //请求数据库信息
        $api.metadata
            .executeFunction({
                type: connItem.type,
                pluginId: connItem.properties.pluginId,
                params: params,
            })
            .then((res) => {
                catalogList.value = res.data;
                resolve()
            })
        //请求该连接得所有元数据信息
        $api.metadata
            .executeFunction({
                type: 'allMetadataEditorKey',
                pluginId: connItem.properties.pluginId,
                params: params,
            })
            .then((res) => {
                dbs.value = res.data
            })

  })  
};

const editorMounted = (editor) => {
    console.log('editor实例加载完成', editor)

};
const sqlQueryHandle = () => {
    resultLoading.value = true
    resultTabs.value.activeTab = 'message'
    executeResult.value = [];
    executeResultTabs.value = []
    const selectSql = sqlEditor.value.getSelectionVal();
    const executeParams = { script: selectSql ? selectSql : sql.value, noPage: globalPageState.value };
    const params = { connId: connectionId.value, catalog: catalogName.value, executeParams: executeParams };
    executeState.value = true
    //请求后台获取子节点数据
    $api.sqlDatabase
        .executeSqlScript(params)
        .then((res) => {
            executeResult.value = res.data;
            executeResultTabs.value = executeResult.value.filter(item => item.success && item.columns).filter((item, index) => {
                item.index = index;
                return true;
            })
            navbar.value.select(0)
        })
        .finally(() => {
             resultLoading.value = false
            executeState.value = false
        })
};
const onInputField = async (dbName, tableName) => {
    const fields = await getTableCloumn(dbName, tableName)
    return fields
}
/**
 * 异步获取表字段
 */
const getTableCloumn = (dbName, tableName) => {
    const connItem = connList.value.find(value => value.id == connectionId.value);
    if (connItem == undefined || !dbName || !tableName) {
        return []
    }
    const params = { catalog: dbName, tableName: tableName, connId: connectionId.value };
    return new Promise((resolve, reject) => {
        //请求该连接得所有元数据信息
        $api.metadata
            .executeFunction({
                type: 'columnsEditorKey',
                pluginId: connItem.properties.pluginId,
                params: params,
            })
            .then((res) => {
                resolve(res.data)
            })
    })
}

const formatSqlHandle=()=>{
    sqlEditor.value.setValue( format(sql.value,{ language: 'sql', indent: '    ' }));
}



const executeSqlScript = (sql) => {
    return new Promise((resolve, reject) => {
        const executeParams = { script: sql, noPage: true };
        const params = { connId: connectionId.value, catalog: catalogName.value, executeParams: executeParams };
        //请求后台获取子节点数据
        $api.sqlDatabase
            .executeSqlScript(params)
            .then((res) => {
                return resolve(res);
            })
            .catch(e => {
                reject(e)
            })

    });

}
</script>

<style lang="scss" scoped>
.workbeanch-sql-editor-box {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    background-color: #f6f8f9;

    .workbeanch-editor-tags {
        flex: 1;
    }

    .workbeanch-toolbar {
        flex-direction: column-reverse;
        width: 100%;
    }

    .sql-editor-toolbar {
        margin-left: 8px;
    }

}


.workbeanch-sql-editor-box .sql-editor {
    position: relative;
    flex: 1;
    margin: 3px 0px 0px 0px;
}

.sql-editor .magic-monaco-editor-wrapper {
    position: absolute;
    top: 0px;
    left: 0;
    right: 0;
    bottom: 0;
}

.workbeanch-toolbar .magic-navbar {
    display: flex;
    flex-direction: column-reverse;
    flex: 1;

    ul {
        margin: 0px 0px
    }
}

:deep(.margin-view-overlays) {
    background: #f6f8f9;
}

// :deep(.el-table .cell, .el-table th div) {
//     padding: 0 !important;
// }

// :deep(.el-table tr td .cell) {
//     padding: 5px 2px !important;
// }

// :deep(.el-table .cell, .el-table th div, .el-table--border td:first-child .cell, .el-table--border th:first-child .cell) {
//     padding-left: 0 !important;
// }

.sql-execute-result-box {
    width: 100%;


    .el-table__body-wrapper {
        background-color: #ddd;
    }

    .el-table__body-wrapper::-webkit-scrollbar {
        width: 8px !important;
        height: 8px !important;
    }

    // :deep(.el-tabs) {
    //     --el-tabs-header-height: 25px;
    //     --el-font-size-base: 12px;
    //     font-size: 12px;
    // }

    // :deep(.el-tabs__header) {
    //     margin: 0 0 5px;
    // }

    // :deep(.el-tabs__nav) {
    //     border-radius: 0px 0px 0 0;
    // }

    :deep(.vxe-switch) {
        padding: 0px;
    }

    // :deep(.cell) {}
}

/*滚动条整体部分*/
.mytable-scrollbar ::-webkit-scrollbar {
    width: 12px;
    height: 12px;
}

/*滚动条的轨道*/
.mytable-scrollbar ::-webkit-scrollbar-track {
    background-color: #FFFFFF;
}

/*滚动条里面的小方块，能向上向下移动*/
.mytable-scrollbar ::-webkit-scrollbar-thumb {
    background-color: #bfbfbf;
    border-radius: 5px;
    border: 1px solid #F1F1F1;
    box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
}

.mytable-scrollbar ::-webkit-scrollbar-thumb:hover {
    background-color: #A8A8A8;
}

.mytable-scrollbar ::-webkit-scrollbar-thumb:active {
    background-color: #787878;
}

/*边角，即两个滚动条的交汇处*/
.mytable-scrollbar ::-webkit-scrollbar-corner {
    background-color: #FFFFFF;
}

.execute-result-table-toolbar {
    padding: 0px 5px 5px 5px;
}

.result-box {

    height: 100%;
}

.result-message {
    padding-bottom: 10px;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
    height: 36px;
    padding-right: 10px;

    .i{
        padding-right: 2px;
    }
}
</style>